#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Project : chat_model 
# @File    : session_logic.py
# @IDE     : PyCharm 
# @Author  :ZH
# @Time    : 2025/1/3 17:22
__all__ = ['session_logic']

from tortoise.expressions import Q

from apps import cruds
from apps.models import User
from apps.utils.enumerate import SessionTypeEnum


class SessionLogic:
    def __init__(self):
        self.crud = cruds.session_crud

    async def session_list(self, user: User, session_type: SessionTypeEnum, page: int = 1, limit: int = 10,
                           name: str = None):
        query_sql = self.crud.model.filter(is_delete=False, session_type=session_type.value, user_id=user.id)
        if name:
            query_sql = query_sql.filter(Q(session_name__icontains=name) | Q(description__icontains=name))
        count = await query_sql.count()
        if count:
            data = await query_sql.offset((page - 1) * limit).limit(limit).order_by('-update_date').all()
        else:
            data = []
        return count, data

    async def session_create(
            self, user: User, session_type: SessionTypeEnum, model_id: int, session_name: str = '新建会话',
            description: str = None
    ):
        return await self.crud.create(obj_in={
            'session_name': session_name,
            'description': description,
            'user_id': user.id,
            'session_type': session_type,
            'model_id': model_id
        })

    async def session_object(self, session_id: int, user: User, session_type: SessionTypeEnum):
        return await self.crud.model.filter(
            is_delete=False, session_type=session_type.value, user_id=user.id, id=session_id
        ).first()

    async def session_delete(self, session_id: int, user: User):
        return await self.crud.model.filter(
            is_delete=False, user_id=user.id, id=session_id
        ).update(is_delete=True)


session_logic = SessionLogic()
